/*
The MIT License

Copyright (c) 2010 Guillaume Florimond (www.valhalla.fr)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

package fr.valhalla.vcrypt.cyphers;

/**
 * Rot13
 * Crypt message with the Rot13 algorithm.
 * Rot 13 algorithm rotates 13 times each letter of a text string
 * (A, the 1st letter, becomes M, the 13th letter) from left to
 * right (cypher : A to M) and from right to left (decypher : M to A)
 * This is known as the 'Gaius Julius Caesar cypher', used in the Gallic wars.
 *      Rot13 r = new Rot13();
 *      r.setInput("abcd"); // injects a message to convert
 *      r.crypt(); // rotates the message
 *      String result = r.getOutput(); // returns the result result = nopq
 * @author Guillaume Florimond < gf@valhalla.fr > < www.valhalla.fr >
 */
public class Rot13 extends Cypher {

    public Rot13() {
        super();
    }

    @Override
    public void crypt() {
        this.out = rotate(this.in);
    }

    @Override
    public void decrypt() {
        this.out = rotate(this.in);
    }

    private String rotate(String s){
        String msg = "";
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if       (c >= 'a' && c <= 'm') c += 13;
            else if  (c >= 'n' && c <= 'z') c -= 13;
            else if  (c >= 'A' && c <= 'M') c += 13;
            else if  (c >= 'A' && c <= 'Z') c -= 13;
            msg += c;
        }
        return msg;
    }

}
